import React, { PureComponent } from 'react';
import { Row, Col, Input, Button, List, Card, Icon, Modal } from 'antd';
import classnames from 'classnames';
import { connect } from 'react-redux';
import { FormattedMessage } from 'react-intl';
import messages from '@i18n/messages';
import { apiAction } from '../redux/actions';
import ACTION_TYPE from '../redux/constant/action-types';
import Detail from './Detail';
import { API } from './model';
import './index.less';

function mapStateToProps(state) {
  return {
    apiProviders: state.apiProvider,
    addApiLoading: state.loading[ACTION_TYPE.REQUSET_ADD_API_PROVIDER],
    updateApiLoading: state.loading[ACTION_TYPE.REQUEST_UPDATE_API_PROVIDER],
  };
}
function mapDispatchToProps(dispatch) {
  return {
    add: api => dispatch(apiAction.requestAdd(api)),
    remove: api => dispatch(apiAction.requestRemove(api)),
  };
}
@connect(
  mapStateToProps,
  mapDispatchToProps
)
class APIProvider extends PureComponent {
  state = {
    newApiName: '',
    selectedId: undefined,
    addmodel: false,
  };

  onNewApiNameChange = event => {
    const { value } = event.target;
    this.setState({
      newApiName: value,
    });
  };

  onDeleteApi = (event, api) => {
    event.stopPropagation();
    Modal.confirm({
      title: '删除api接口',
      content: `确定删除接口名称为${api.name}的接口？`,
      onOk: () => {
        if (this.state.selectedId === api.id) {
          this.setState({
            selectedId: undefined,
          });
        }
        this.props.remove(api);
      },
    });
  };

  onSelectItem = item => {
    this.setState({
      selectedId: item.id,
    });
  };

  addNewProvider = () => {
    const { newApiName } = this.state;
    if(!newApiName){
      return Modal.error({ content: '请输入接口名称' });
    }
    const newApi = API.create({ name: newApiName });
    this.setState({
      addmodel: false, 
    });
    this.props.add(newApi);
  };
  
  save = () => {
    this.child.save();
  };

  onRef = (ref) => {
    this.child = ref;
  }

  renderDetail = api => {
    if (!api) {
      return null;
    }
    return <Detail onRef={this.onRef} api={api} />;
  };

  render() {
    const { newApiName, selectedId, addmodel } = this.state;
    const { apiProviders, addApiLoading, updateApiLoading } = this.props;
    const selectedApi = apiProviders.find(api => api.id === selectedId);
    return (
      <div>
        <Row className="api-provider">
          <Col className="api-provider-list" span={6}>
            <Card
              title="已添加接口列表" extra={
                <Button
                  type="primary" onClick={() => {
                    this.setState({ addmodel: true }); 
                  }}
                >添加接口
                </Button>
              }
            >
              <div className="api-provider-header">
                <List
                  dataSource={apiProviders}
                  renderItem={item => (
                    <List.Item
                      onClick={() => this.onSelectItem(item)}
                      actions={[
                        <Icon
                          style={{ cursor: 'pointer' }}
                          onClick={event => this.onDeleteApi(event, item)}
                          type="delete"
                        />,
                      ]}
                      className={classnames('list-item', {
                        selected: item.id === selectedId,
                      })}
                    >
                      <div>{item.name}</div>
                    </List.Item>
                  )}
                />
                <Modal
                  visible={addmodel}
                  onOk={this.addNewProvider}
                  okText="确认"
                  confirmLoading={addApiLoading}
                  onCancel={() => {
                    this.setState({ addmodel: false }); 
                  }}
                >                  
                  <span
                    style={{ marginRight: 5 }}
                  >
                    <FormattedMessage {...messages.apiName} />
                  </span>
                  <Input
                    onChange={this.onNewApiNameChange}
                    value={newApiName}
                    style={{ width: 150 }}
                  />
                  {/* <Button
                    style={{ marginLeft: 15 }}
                    loading={addApiLoading}
                    onClick={this.addNewProvider}
                    type="primary"
                  >
                    <FormattedMessage {...messages.addNewApi} />
                  </Button> */}
                </Modal>
              </div>
            </Card>
          </Col>
          <Col className="api-provider-list" span={18}>
            <Card
              title="接口参数配置" span={18}
              extra={
                <Button
                  onClick={this.save}
                  icon="save"
                  type="primary"
                  loading={updateApiLoading}
                >
            保存
                </Button>}
            >
              <div className="api-provider-header">                
                {this.renderDetail(selectedApi)}
              </div>
            </Card>
          </Col>
        </Row>
      </div>
    );
  }
}

export default APIProvider;
